package com.fingard.dsp.bank.directbank.abc02;

import com.fingard.dsp.bank.directbank.bankInterface.IBalance;
import com.fingard.dsp.bank.reqrespobj.balance.Req7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.Req7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsBalDetail;
import com.fingard.dsp.bank.reqrespobj.enumeration.ENDirectRight;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.List;

@Component("ABC02Balance")
public class ABC02Balance extends ABC02Base implements IBalance {
    @Override
	public RetAts7506BalQry d_7506_BalQry(Req7506BalQry p_req7506) throws Exception {
	    p_req7506.readRecord();
	    if (p_req7506.readedDetail.isDeposit) {
			return qryDepositBalQry(p_req7506);
		} else {
			return qry7506BalQry(p_req7506);
		}
	}
	
	/**
	 * 参考文档:现金管理银企直连接入开发手册V1.2.2.wps
	 * 开发接口:7.56	查询定期存款账户余额（CQRA08）
	 * 
	 * @param p_req7506
	 * @return
	 * @throws Exception
	 */
	public RetAts7506BalQry qryDepositBalQry(Req7506BalQry p_req7506) throws Exception {
        RetAts7506BalQry retAts = new RetAts7506BalQry(p_req7506.reqHeader);
        retAts.writeStart();
        
        try {
            ABC02Header bankHeader = new ABC02Header();
            bankHeader.CCTransCode = "CQRA08";
            bankHeader.ReqSeqNo = p_req7506.reqHeader.transSeqID;
            p_req7506.resetReadMode();
            while (p_req7506.readRecord()) {//农行不支持批量查询，逐个查询
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                writeCommonHeader(xmlWriter, bankHeader);
                xmlWriter.writeStartElement("Cmp");
                xmlWriter.writeElementString("DbAccNo", getAbcAccNo(p_req7506.readedDetail.actNum));
                String dbProv = p_req7506.readedDetail.actArea;
                String prdSeq = "";
                if ("true".equals(getBankConfig().getValueAsString("useActInfoSetOwnerArea").toLowerCase())) {
                    if ((p_req7506.readedDetail.actNum.indexOf('-') > 0 && p_req7506.readedDetail.actNum.length() == 18) || (p_req7506.readedDetail.actNum.length() == 17)) {
                        String[] array = p_req7506.readedDetail.actNum.split("-");
                        dbProv = array[0];
                        prdSeq = array[2];
                    }
                }
                xmlWriter.writeElementString("DbProv", dbProv);
                xmlWriter.writeElementString("DbCur", convertCurToBank(p_req7506.readedDetail.actCur));
                xmlWriter.writeEndElement();
                xmlWriter.writeStartElement("Corp");
                xmlWriter.writeElementString("PrdSeq", prdSeq);
                xmlWriter.writeElementString("DbAccName", p_req7506.readedDetail.actName);
                xmlWriter.writeElementString("CshDraFlag", "0");
                xmlWriter.writeEndDocument();
                
                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpRetCode = tmpBkReader.getFirstText("/ap/RespCode");
                        String tmpRetRxtInfo = tmpBkReader.getFirstText("/ap/RxtInfo");
                        if ("0000".equals(tmpRetCode)) {
                        	String tmpDataMFS = tmpBkReader.getFirstText("/ap/Cmp/RespPrvData");
                            if (tmpDataMFS != null) {
                                List<String> tmpArrayList = getResult(tmpDataMFS);
                                
                                Iterator<String> lists = tmpArrayList.iterator();
                        		while(lists.hasNext()) {
                        			String eachLine = lists.next();
                        			if (eachLine.contains("seqno")) {
                        				continue;
                        			}
                        			String[] eachArray = eachLine.split("\\|");
                        			
                        			RetAtsBalDetail tmpRetDetail = new RetAtsBalDetail();
                                    tmpRetDetail.actNum = p_req7506.readedDetail.actNum;
                        			tmpRetDetail.respCode = "0";
                                    tmpRetDetail.actArea = p_req7506.readedDetail.actArea;
                                    tmpRetDetail.actCur = p_req7506.readedDetail.actCur;
                                    tmpRetDetail.actNum = p_req7506.readedDetail.actNum;
                                    tmpRetDetail.currBal = eachArray[2];
                                    tmpRetDetail.availBal = eachArray[2];
                                    retAts.writeRetDetail(tmpRetDetail, p_req7506.isBatch);
                        		}
                            } else {
                            	retAts.writeRespCode("-1");
                            	retAts.writeBatRespInfo("数据为空");
                            }
                        } else {
                        	retAts.writeRespCode("-1");
                        	retAts.writeBatRespInfo(tmpRetRxtInfo);
                        }
                    } else {
                    	retAts.writeRespCode("-1");
                        retAts.writeBatRespInfo(tmpSbMsg.toString());
                    }
                } else {
                	retAts.writeRespCode("-1");
                	retAts.writeBatRespInfo(tmpStrRet[1]);
                }
            }
        } catch (Exception ex) {
        	ex.printStackTrace();
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(ex.getMessage());
            WriteBankLogLn(ex);
        }
        retAts.writeEnd();
        return retAts;
    }
	
    public RetAts7506BalQry qry7506BalQry(Req7506BalQry p_req7506) throws Exception {//余额查询
        RetAts7506BalQry retAts = new RetAts7506BalQry(p_req7506.reqHeader);
        retAts.writeStart();
        try {
            ABC02Header bankHeader = new ABC02Header();
            bankHeader.CCTransCode = "CQRA06";
            bankHeader.ReqSeqNo = p_req7506.reqHeader.transSeqID;
            p_req7506.resetReadMode();
            while (p_req7506.readRecord()) {//农行不支持批量查询，逐个查询
                RetAtsBalDetail tmpRetDetail = new RetAtsBalDetail();
                tmpRetDetail.actNum = p_req7506.readedDetail.actNum;

                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                //写入通用的头部节点
                writeCommonHeader(xmlWriter, bankHeader);
                xmlWriter.writeStartElement("Cmp");
                xmlWriter.writeElementString("DbAccNo", getAbcAccNo(p_req7506.readedDetail.actNum));
                String dbProv = p_req7506.readedDetail.actArea;
                if ("true".equals(getBankConfig().getValueAsString("useActInfoSetOwnerArea").toLowerCase())) {
                    if ((p_req7506.readedDetail.actNum.indexOf('-') > 0 && p_req7506.readedDetail.actNum.length() == 18) || (p_req7506.readedDetail.actNum.length() == 17)) {
                        dbProv = p_req7506.readedDetail.actNum.substring(0, 2);
                    }
                }
                xmlWriter.writeElementString("DbProv", dbProv);
                xmlWriter.writeElementString("DbCur", convertCurToBank(p_req7506.readedDetail.actCur));
                xmlWriter.writeEndElement();
                xmlWriter.writeEndDocument();
                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpRetCode = tmpBkReader.getFirstText("/ap/RespCode");
                        String tmpRetInfo = tmpBkReader.getFirstText("/ap/RespInfo");
                        String tmpRetRxtInfo = tmpBkReader.getFirstText("/ap/RxtInfo");
                        if (tmpRetCode != null && tmpRetCode.equals("0000")) {
                            if (tmpBkReader.read("/ap/Acc")) {
                                tmpRetDetail.respCode = "0";
                                tmpRetDetail.actCur = p_req7506.readedDetail.actCur;
                                tmpRetDetail.actNum = p_req7506.readedDetail.actNum;
                                tmpRetDetail.availBal = tmpBkReader.readedXElement.getSingleText("AvailBal");
                                tmpRetDetail.currBal = tmpBkReader.readedXElement.getSingleText("Bal");
                                tmpRetDetail.frozenBal = tmpBkReader.readedXElement.getSingleText("FrzBal");
                            }
                        } else {
                            tmpRetDetail.respCode = "-1";
                            if (!StringHelper.isNullOrEmpty(tmpRetRxtInfo)) {
                                tmpRetDetail.respInfo = tmpRetRxtInfo;
                            } else {
                                tmpRetDetail.respInfo = tmpRetInfo;
                            }
                        }
                    } else {
                        tmpRetDetail.respCode = "-1";
                        tmpRetDetail.respInfo = tmpSbMsg.toString();
                    }
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpStrRet[1];
                }

                //判断账号有现金池权限是，查询现金池余额接口
                if(p_req7506.readedDetail.directRight.contains(ENDirectRight.CASHPOOLS.getValue())) {
                    qry7506CashPoolBal(p_req7506, tmpRetDetail);
                }
                retAts.writeRetDetail(tmpRetDetail, p_req7506.isBatch);
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts.writeEnd();
        return retAts;
    }
    /**
     * 现金池余额查询
     */
    private void qry7506CashPoolBal(Req7506BalQry p_req7506, RetAtsBalDetail tmpRetDetail){
        ABC02Header bankHeader = new ABC02Header();
        bankHeader.CCTransCode = "CQRA04";
        bankHeader.ReqSeqNo = p_req7506.reqHeader.transSeqID;
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        try {
            //写入通用的头部节点
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeStartElement("Cmp");
            xmlWriter.writeElementString("DbAccNo", getAbcAccNo(p_req7506.readedDetail.actNum));
            String dbProv = p_req7506.readedDetail.actArea;
            if ("true".equals(getBankConfig().getValueAsString("useActInfoSetOwnerArea").toLowerCase())) {
                if ((p_req7506.readedDetail.actNum.indexOf('-') > 0 && p_req7506.readedDetail.actNum.length() == 18) || (p_req7506.readedDetail.actNum.length() == 17)) {
                    dbProv = p_req7506.readedDetail.actNum.substring(0, 2);
                }
            }
            xmlWriter.writeElementString("DbProv", dbProv);
            xmlWriter.writeElementString("DbCur", convertCurToBank(p_req7506.readedDetail.actCur));
            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/ap/RespCode");
                    if (tmpRetCode != null && tmpRetCode.equals("0000")) {
                        if (tmpBkReader.read("/ap/Acc")) {
                            tmpRetDetail.cashPoolAvailBal = tmpBkReader.readedXElement.getSingleText("Bal");
                            tmpRetDetail.cashPoolBal = tmpBkReader.readedXElement.getSingleText("Bal");
                        }
                    }
                }
            }
        }catch (Exception e){
            WriteBankLogLn("现金池余额查询异常:" +e.getMessage());
        }
    }

    @Override
    public RetAts7505HisBalQry d_7505_BalQry(Req7505HisBalQry p_req7505) throws Exception {
        return null;
    }
}
